package com.example.p250201.controller;


import com.example.p250201.common.AppHttpCodeEnum;
import com.example.p250201.common.ResponseResult;
import com.example.p250201.entity.RegisterDto;
import com.example.p250201.entity.RegisterSo;
import com.example.p250201.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 袁可
 * @since 2025-02-03
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService iLoginService;

    @RequestMapping("/register")
    public ResponseResult register(@RequestBody RegisterDto registerDto){
        // 字符长度校验，交给前端，

        // 形参校验，必填不能为空，唯一不能已存在，
        // 形参校验，必填不能为空，

        if (registerDto == null) {
            log.error("注册失败，输入不能为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_INFORM_NULL);
        }
        // 昵称不能为空
        if (registerDto.getNickname() == null || registerDto.getNickname() .equals("")){
            log.error("注册失败，昵称不能为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_NICKNAME_NULL);
        }
        // 密码不能为空
        if (StringUtils.isBlank(registerDto.getPassword())){
            log.error("注册失败，密码不能为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_PASSWORD_NULL);
        }
        // 需要手机号或邮箱
        if (StringUtils.isBlank(registerDto.getPhone())||StringUtils.isBlank(registerDto.getEmail())) {
            log.error("注册失败，需要手机号或邮箱");
            return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_NEED_PHONE_OR_EMAIL);
        }

        // 属性拷贝
        RegisterSo registerSo=new RegisterSo();
        BeanUtils.copyProperties(registerDto, registerSo);

        // 信息补充
        registerSo.setCreator("localhost");

        AppHttpCodeEnum enums= null;
        try {
            enums = iLoginService.insert(registerSo);
        } catch (Exception e) {
            log.error("注册失败，service方法异常",e);
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.REGISTER_ERROR);
        }

        return ResponseResult.response(enums);
    }

}
